package logic

import (
	"context"
	"github.com/olivere/elastic/v7"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"month/models"

	"month/rpc/internal/svc"
	"month/rpc/month"

	"github.com/zeromicro/go-zero/core/logx"
)

type EsSendLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewEsSendLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EsSendLogic {
	return &EsSendLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 塞入数据
func (l *EsSendLogic) EsSend(in *month.EsSendRequest) (*month.EsResponse, error) {
	// todo: add your logic here and delete this line

	db, err := gorm.Open(mysql.Open("root:q025l6263@tcp(43.143.123.142:3306)/2107a"), &gorm.Config{})
	if err != nil {
		return &month.EsResponse{
			Code:    400,
			Message: "数据库连接失败",
		}, nil
	}

	var fe = models.Fgit{}

	//开启事物
	tx := db.Logger
	tx.Info(context.Background(), "fgit", fe)

	if db.Error != nil {
		//回滚
		db.Rollback()
	}

	var f []models.Fgit
	err = db.Raw("select * from `fgit`").Scan(&f).Error
	if err != nil {
		return &month.EsResponse{
			Code:    400,
			Message: "数据库查询失败",
		}, nil
	}

	esClient, err := elastic.NewClient(elastic.SetURL("http://43.143.123.142:9200"), elastic.SetSniff(false))
	if err != nil {
		return &month.EsResponse{
			Code:    400,
			Message: "elastic连接失败",
		}, err
	}

	for _, v := range f {
		_, err := esClient.Index().Index("fgit").Id(string(v.Id)).BodyJson(v).Do(context.Background())
		if err != nil {
			return &month.EsResponse{
				Code:    400,
				Message: "向es中添加数据失败",
			}, err
		}
	}

	return &month.EsResponse{
		Code:    200,
		Message: "成功",
	}, nil
}
